package main

import (
	"fmt"
	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
	"github.com/spf13/viper"
	"gopkg.in/natefinch/lumberjack.v2"
	"os"
	"path/filepath"
	"strconv"
)

func setupLog() {
	writer := &lumberjack.Logger{
		Filename:   viper.GetString("log.filename"),
		MaxSize:    viper.GetInt("log.max_size"),
		MaxBackups: viper.GetInt("log.max_backups"),
		MaxAge:     viper.GetInt("log.max_age"),
		LocalTime:  true,
	}

	zerolog.CallerMarshalFunc = func(file string, line int) string {
		return filepath.Base(file) + " : " + strconv.Itoa(line)
	}

	consoleWriter := zerolog.ConsoleWriter{Out: os.Stdout}
	multi := zerolog.MultiLevelWriter(consoleWriter, writer)
	log.Logger = zerolog.New(multi).With().Caller().Timestamp().Logger()
	zerolog.SetGlobalLevel(zerolog.Level(viper.GetInt("log.level")))
	if viper.GetBool("log.restart_new") {
		err := writer.Rotate()
		if err != nil {
			fmt.Printf("writer.Rotate failed: %v\n", err)
			return
		}
	}

}

func setupConfig() {
	viper.SetConfigName("config")
	viper.SetConfigType("toml")
	viper.AddConfigPath(".")

	viper.SetDefault("log.filename", "./log/log.txt")
	viper.SetDefault("log.level", 0)
	viper.SetDefault("log.restart_new", false)
	viper.SetDefault("log.max_size", 100)
	viper.SetDefault("log.max_backups", 10)
	viper.SetDefault("log.max_age", 31)

	viper.SetDefault("capture.max_body_size", 10)
	viper.SetDefault("capture.timeout", 30)

	if err := viper.ReadInConfig(); err != nil {
		if _, ok := err.(viper.ConfigFileNotFoundError); ok {
			fmt.Println("config file not found.")
			os.Exit(1)
		} else {
			fmt.Printf("viper ReadInConfig() failed: %v\n", err)
		}
	}
}
